#!/usr/bin/python3
# -*- coding: utf-8 -*-

import yaml
from lib.gitclient import GitClient

def parse_yaml_file(file_path):
    with open(file_path, 'r') as file:
        data = yaml.safe_load(file)
    return data


def main():
    config = parse_yaml_file('config.yaml')
    gitClient = GitClient(config.get('gitlab').get('url'), config.get('gitlab').get('access_token'))

    base_branch = config.get('base_branch')
    target_branch = config.get('target_branch')	
    print(f"base_branch={base_branch}")
    print(f"target_branch={target_branch}")
    
    # print("------------------projects----------------")
    projects = config.get('projects')
    for project in projects:
        project_id = gitClient.GetProjectID(project.get('name'))
        print(f"------------------id:{project.get('id')} vs {project_id} --- {project.get('name')}----------------")

        exist = gitClient.existBranch(project_id, target_branch)
        if exist:
            same = gitClient.isSameBranch(project_id, target_branch, base_branch)
            if not same:
                print(f"*******************应该删除 {target_branch}")
                gitClient.DeleteBranch(project_id, target_branch)
                gitClient.createBranch(project_id, base_branch, target_branch)
        else:
            gitClient.createBranch(project_id, base_branch, target_branch)

if __name__ == "__main__":
    main()